package com.ys.ffms.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ys.ffms.common.Result;
import com.ys.ffms.pojo.PO.UserPO;
import com.ys.ffms.pojo.User;
import com.ys.ffms.pojo.VO.UserExcelVO;
import com.ys.ffms.service.UserService;
import com.ys.ffms.utils.MD5Util;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 测试项目启动
     * @return
     */
    @ApiOperation(value = "测试启动",httpMethod = "GET")
    @GetMapping("/test")
    public String test(){
        return "项目启动成功....";
    }

    /**
     * login 登录
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        //按照名字查询记录
        User user1 = userService.queryUserByName(user.getUserId());
        //查询用户是否存在
        if(user1==null){
            return Result.error("500","用户不存在!");
        }
        if(user1.getStatus()!=0){
            return Result.error("500","该账号已禁用!");
        }
        //校验密码
        String s = userService.checkPwd(user.getUserId());//数据库查询的MD加密密码

        if(!MD5Util.passwordIsTrue(user.getPassword(),s)){
            return Result.error("500","密码错误!");
        }
        //成功登录
        return Result.success(user1,"登录成功!");
    }

    /**
     * 按照id查询用户数据
     * @param id
     * @return
     */
    @GetMapping("/findUserById/{id}")
    public User findUserById(@PathVariable("id") Integer id){
        User user = userService.findUserById(id);
        return user;
    }


//    @PostMapping("/onEdit")
//    public Result<?> onEdit(@RequestBody User user){
//        Result<?> result = userService.onEdit(user);
//        if(result!=null){
//            return Result.success(result);
//        }
//        else {
//            return Result.error("500","修改失败!");
//        }
//    }
    /**
     * 按照实体修改个人信息
     * @param userPO
     * @return
     */
    @PostMapping("/onEditByEntity")
    public Result<?> onEditByEntity(@RequestBody UserPO userPO){
        Result<?> result = userService.onEditByEntity(userPO);
        if(result!=null){
            return Result.success(result);
        }
        else {
            return Result.error("500","修改失败!");
        }
    }

    /**
     * 分页查询所有的用户
     * @return
     */
    @GetMapping("/findAllByPage")
    public Result<Page<User>> findAllByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestParam(defaultValue = "") String name,
                                      @RequestParam(defaultValue = "") String status){
        Page<User> page = userService.findAllBill(pageNum,pageSize,name,status);
        return Result.success(page);
    }

    /**
     * 添加用户
     * @param userPO
     * @return
     */
    @PostMapping("/addUser")
    public Result<UserPO> addUser(@RequestBody UserPO userPO){
        if(userPO!=null){
            int i = userService.addUser(userPO);
            return Result.success(userPO,"添加成功!");
        }
        return Result.error("500","未知错误!");
    }

    /**
     * 按照id和状态修改用户状态
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateUserStatus/{id}/{status}")
    public Result<?> updateUserStatus(@PathVariable Integer id,@PathVariable Integer status){
        return userService.updateUserStatus(id,status);
    }
    /**
     * 按照实体删除对应数据
     * @param user
     * @return
     */
    @PostMapping("/delUserById")
    public Result<User> delUserById(@RequestBody User user){
        return userService.delUserById(user);
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PostMapping("/editUser")
    public Result<?> editUser(@RequestBody User user){
        return userService.onEdit(user);
    }

    /**
     * 数据导出
     * @param response
     */
    @GetMapping("/userDownLoad")
    public String getXlsx(HttpServletResponse response) throws IOException {
        List<UserExcelVO> list = userService.findAll();
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        String fileName = "用户信息";
        Sheet sheet = new Sheet(1, 0,UserExcelVO.class);
        //设置自适应宽度
        sheet.setAutoWidth(Boolean.TRUE);
        // 第一个 sheet 名称
        sheet.setSheetName("全部用户数据");
        writer.write(list, sheet);
        //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
        writer.finish();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        out.flush();
        return null;
    }
//    @GetMapping(value = "/userDownLoad")
//    public void userDownLoad(HttpServletResponse response){
//        //查出所有数据
//        List<UserExcelVO> dataList = userService.findAll();
//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
//        try {
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode("测试", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
////            response.setHeader("Content-disposition", "attachment;filename=" + new String( ) + ".xlsx");
//            // 这里需要设置不关闭流
//            EasyExcel.write(response.getOutputStream(), UserExcelVO.class)
//                    .autoCloseStream(Boolean.FALSE)
//                    .sheet("模板")
//                    .doWrite(dataList);
//            response.getOutputStream().flush();
//            response.getOutputStream().close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            // 重置response
//            response.reset();
//            response.setContentType("application/json");
//            response.setCharacterEncoding("utf-8");
//            //JsonResponse.fail().setMsg("导出失败");
//        }
//    }

    /**
     * 全部家庭成员总数
     * @return
     */
    @GetMapping("/findAllMembers")
    public Result<?> findAllMembers(){
        int count = userService.findAllMembers();
        return Result.success(count,"总成员数:"+count);
    }
}
